#!/usr/bin/env python
# *-* coding: latin-1 *-*
#
#       youtube_syncronizer
#
#       Copyright 2009 Frederico Rodrigues Chevitarese <fchevitarese@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

from django_youtube_syncronizer.models import *
from django.conf import settings
from xml.dom import minidom
from time import *

import gdata.youtube
import gdata.youtube.service
import urllib

#import datetime
#import sys

"""
    makeEmbeded()
    This function takes the video code and generates the code to embed in the page and display the player.
    Esta função pega o código do vídeo e gera o embeded para ser exibido na sua template.
"""
def make_embeded(url):
    delimiter = url.find("?")
    videoCode = url[:delimiter]
    #print "Codigo p embeded : %s" %videoCode
    embCode = ("""<object width="445" height="364"><param name="movie" value="%s&hl=pt-br&fs=1&rel=0&color1=0x234900&color2=0x4e9e00&border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="%s&hl=pt-br&fs=1&rel=0&color1=0x234900&color2=0x4e9e00&border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="445" height="364"></embed></object>""" % (videoCode, videoCode))
    return embCode

"""
    Limpa a url retornada pelo Gdata...
"""
def clear_url(url):
    delimiter = url.find('&')
    video_url = url[:delimiter]
    return video_url

"""
    gettingUrls(feed)
    Grab the url returned by the "XML" and cut only what is necessary to mount the embedded code to be used by the "views".
    Pega os dados necessários retornados pelo XML
"""
#def getting_urls(feed):
    #data = minidom.parse(urllib.urlopen(feed))
    #link = data.getElementsByTagName('link')
    #for links in link:
        #if links.getAttribute('rel') == 'alternate':
            #results = (links.getAttribute('href'))

    #delimiter = results.find("&")
    #results = results[:delimiter]
    #return results

"""
    youtube_sync(userfeed)

    Synchronizes the videos with the previously registered in the system.
    The API "Youtube" only returns 50 videos per request, so we have to iterate through url increasing the threshold and size of the return.
    The API "Youtube" also limits the amount of videos up to 999, but i don't think anyone has more videos than this. ;)

    Sincroniza os vídeos com um canal previamente cadastrado no sistema ;)
    A API do Youtube retorna apenas 50 vídeos por requisição. Sendo assim, temos que iterar pela url incrementando o delimitador e o tamanho do retorno.
    A API do Youtube limita o montante de vídeos para 999, mas eu não acredito que alguém tenha mais vídeos que isto ;)

"""
def youtube_sync(userfeed):
    if settings.YOUTUBE_SYNC_LANG == 'BR':
        print(u'Pegando os dados do canal ...')
    else:
        print('Getting data ...')

    yt = gdata.youtube.service.YouTubeService()
    initial = 1
    size = 50
    increment = 50

    for i in range(1, 999):
        uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads/?&start-index=%s&max-results=%s' %(userfeed ,initial, size)
        feed = yt.GetYouTubeVideoFeed(uri)

        if feed.entry:
            for entry in feed.entry:

                video = video_data.objects.get(url = clear_url(entry.media.player.url))
                if video:
                    if settings.YOUTUBE_SYNC_LANG == 'BR':
                        print (u'Este vídeo já foi cadastrado!!! %s') %entry.title.text.decode('cp1252')
                    else:
                        print ('That video already exists !!! %s') %entry.title.text
                else:
                    video = video_data.objects.create(
                        videoChannel = userfeed,
                        title = entry.media.title.text,
                        published = entry.published.text[:10],
                        description = entry.media.category[0].text,
                        duration = entry.media.duration.seconds,
                        url = clear_url(entry.media.player.url),
                        embededCode = make_embeded(entry.GetSwfUrl()),
                    )
                    video.save()

                    if settings.YOUTUBE_SYNC_LANG == 'BR':
                         print ('Cadastrado - %s') %video.title
                    else:
                         print ('Saved - %s') %video.title
            initial += increment

        else:
            if settings.YOUTUBE_SYNC_LANG == 'BR':
                print (u'Terminei ... Peguei todos os vídeos do canal %s') %userfeed
            else:
                print ('Finish ... Got all videos of channel %s') %userfeed

            break
